//
//  BLECmdVC.swift
//  BLEManagerSwiftDemo
//
//  Created by Qinsz on 2019/5/24.
//  Copyright © 2019年 Qinsz. All rights reserved.
//

import UIKit

class BLECmdVC: UIViewController,UITableViewDataSource,UITableViewDelegate {

    @IBOutlet weak var contentView: UIView!
    @IBOutlet weak var reqTextView: UITextView!
    @IBOutlet weak var rspTextView: UITextView!
    
    
    private let cmdTableView = UITableView.init()
    
    weak private var weakVC:NordicUpgradeVC?
    
    private var sendContactTasks = Array<KCTOldBLETaskSendContacts>.init()
    
    private let bleShell = KCTSingleBLEShell.sharedInstance
    
    private let functionNames:[KCTBLEFunctionName] = [.SetAltitude,
                                                      .SetBPCalibrationStart,
                                                      .SetStepDistance,
                                                      .SetUserInfo,
                                                      .SetSysInfo,
                                                      .FindDevice,
                                                      .SetTime,
                                                      .SetAlarm,
                                                      .SetSportGoal,
                                                      .SetSedentary,
                                                      .SetDrinkRemind,
                                                      .SetPush,
                                                      .SetExtendedPush,
                                                      .ReqExtendedPush,
                                                      .SendTextMessage,
                                                      .BPCalibrate,
                                                      .SetMenstrualCycle,
                                                      .SetWeather,
                                                      .SetAdvanceWeather,
                                                      .SetCameraOnOff,
                                                      .SetGestureSceenOn,
                                                      .ReqBindAuth,
                                                      .SetDoNotDisturb,
                                                      .SetRemindMode,
                                                      .SetHRCheckConfig,
                                                      .SetUnitsSystem,
                                                      .SetWeatherIndex,
                                                      .InputAssitStart,
                                                      .InputAsistSendMsg,
                                                      .ReadFirmwareInfos,
                                                      .ReadBasicFirmwareInfos,
                                                      .ReqProfileInfo,
                                                      .ReqSettingInfo,
                                                      .ReqPowerInfo,
                                                      .SyncHisSleep,
                                                      .SyncHisHeartRate,
                                                      .SyncHisStep,
                                                      .SyncHisSport,
                                                      .SyncHisBP,
                                                      .SyncHisBO,
                                                      .SyncHisPressure,
                                                      .SyncRealTimeSport,
                                                      .SyncRealTimeSportMode,
                                                      .SyncHisAnalogicECG,
                                                      .SyncHisTemp,
                                                      .ReqSmartSport,
                                                      .SendUrgentNum,
                                                      .SyncContacts,
                                                      .SmartDialSelect,
                                                      .SmartDialList,
                                                      .SendQRString,
                                                      .NordicUpgrade,
                                                      .BKUpgrade,
                                                      .DialPush,
                                                      .MedicineRemind,
                                                      .ESIM,
                                                      .PointerCorrect,
                                                      .Reboot,
                                                      .Reset,
                                                      .AutoTest,
                                                      .ReqBind,
                                                      .ReqUnbind
    ]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        cmdTableView.backgroundColor = UIColor.white
        cmdTableView.delegate = self
        cmdTableView.dataSource = self
        self.contentView.addSubview(cmdTableView)

        // Do any additional setup after loading the view.
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        let tableW:CGFloat = 150.0
        let tableH:CGFloat = self.contentView.frame.size.height - 10*2
        let x:CGFloat = self.contentView.frame.size.width - tableW
        let y:CGFloat = 10.0
        cmdTableView.frame = CGRect.init(x: x, y: y, width: tableW, height: tableH)
    }

    @IBAction func clickBack(_ sender: Any) {
        self.navigationController?.popViewController(animated: true)
    }
    
    @IBAction func clickDisConn(_ sender: Any) {
        bleShell.cancelConnection()
    }
    

    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return functionNames.count
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 60
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "BLECmdCellID")
        if  cell == nil {
            cell = Bundle.main.loadNibNamed("BLECmdCell", owner: nil, options: nil)?.first as? BLECmdCell
        }
        
        var str = NSLocalizedString(functionNames[indexPath.row].rawValue, comment: "")
        let array : Array = functionNames[indexPath.row].rawValue.components(separatedBy: "\n")
        if array.count==2{
            str = NSLocalizedString(array[0], comment: "")+"\n"+array[1]
        }
        
        let cmdCell = cell as! BLECmdCell
        cmdCell.titleLabel.text = str //buttonTitles[indexPath.row]
        return cmdCell
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        tableView.deselectRow(at: indexPath, animated: false)
        
        reqTextView.text = nil
        rspTextView.text = nil
        
        let funcName = functionNames[indexPath.row]
        IPrint("点击功能:\(funcName.rawValue.replacingOccurrences(of: "\n", with: ""))")
        
        switch funcName {
        case .SetAltitude://设置海拔
            let task = KCTOldBLETaskSetAltitude.init {[weak self] (tsk,error) -> (Void) in
                self?.rspTextView.text = ResultContent(title: NSLocalizedString("设置海拔", comment: ""), error: error, rspDes: nil)
            }
            task.altitude = 66
            //UI展示设置参数
            reqTextView.text = ReqContent(title: NSLocalizedString("设置海拔", comment: ""), task: task)
            
            bleShell.resume(baseTask: task)
        
        case .SetBPCalibrationStart://设置血压校准开始
            
            let task = KCTOldBLETaskSetBPCalibrationStart.init {[weak self] (tsk,error) -> (Void) in
                self?.rspTextView.text = ResultContent(title: NSLocalizedString("设置血压校准开始", comment: ""), error: error, rspDes: nil)
            }
            
            //UI展示设置参数
            reqTextView.text = ReqContent(title: NSLocalizedString("设置血压校准开始", comment: ""), task: task)
            
            bleShell.resume(baseTask: task)
            
            
        case .SetStepDistance://设置步距
            
            let phs = [NSLocalizedString("走路的步距(cm)", comment: ""),
                       NSLocalizedString("跑步的步距(cm)", comment: "")]
            
            self.showMultiTextInput(title: NSLocalizedString("设置步距", comment: ""), message: nil, lines: phs.count, placeHolders: phs) {[weak self] (contents) in
                
                if let walkStepDistance = Int(contents[0]) ,
                   let runStepDistance  = Int(contents[1]) {
                    let task = KCTOldBLETaskSetStepDistance.init { [weak self] (tsk,error) -> (Void) in

                        self?.rspTextView.text = ResultContent(title: NSLocalizedString("设置步距", comment: ""), error: error, rspDes: nil)
                    }
                    task.walkStepDistance = walkStepDistance
                    task.runStepDistance = runStepDistance
                    //UI展示设置参数
                    self?.reqTextView.text = ReqContent(title: NSLocalizedString("设置步距", comment: ""), task: task)
                    
                    self?.bleShell.resume(baseTask: task)
                }else{
                    SVProgressHUD.showInfo(withStatus: NSLocalizedString("输入有误", comment: ""))
                }
                
            }
            
        case .SetUserInfo://设置用户信息
            
            let phs = [NSLocalizedString("0-女,1-男", comment: ""),
                       NSLocalizedString("年龄", comment: ""),
                       NSLocalizedString("身高(cm)", comment: ""),
                       NSLocalizedString("体重(kg)", comment: ""),
                       NSLocalizedString("目标步数", comment: ""),
                       NSLocalizedString("运动模式,0-记步,1-跑步,2-骑行,3-爬山", comment: "")]
            
            self.showMultiTextInput(title: NSLocalizedString("设置用户信息", comment: ""), message: nil, lines: phs.count, placeHolders: phs) {[weak self] (contents) in
                
                if let gender = Int(contents[0]),let age = Int(contents[1]),let height = Int(contents[2]),let weight = Int(contents[3]),let goal = Int(contents[4]),let mode = Int(contents[5]){
                    let task = KCTOldBLETaskSetUserInfos.init { [weak self] (tsk,error) -> (Void) in

                        self?.rspTextView.text = ResultContent(title: NSLocalizedString("设置用户信息", comment: ""), error: error, rspDes: nil)
                    }
                    task.gender = gender
                    task.age = age
                    task.height = Float(height)
                    task.weight = Float(weight)
                    task.goal = goal
                    task.goalMode = mode
                    
                    //UI展示设置参数
                    self?.reqTextView.text = ReqContent(title: NSLocalizedString("设置用户信息", comment: ""), task: task)
                    
                    self?.bleShell.resume(baseTask: task)
                }else{
                    SVProgressHUD.showInfo(withStatus: NSLocalizedString("输入有误", comment: ""))
                }
                
            }
            
        case .SetSysInfo://系统设置
            
            let cs = ["1","0","20","1"]
            
            let phs = [NSLocalizedString("系统语言.0~255", comment: ""),
                       NSLocalizedString("0:24小时制, 1:12小时制", comment: ""),
                       NSLocalizedString("亮屏时间(秒)", comment: ""),
                       NSLocalizedString("是否配对.0-不配对,1-配对", comment: "")]
            
            self.showMultiTextInput(title: NSLocalizedString("系统设置", comment: ""), message: nil, lines: cs.count, placeHolders: phs, contents: cs) {[weak self] (contents) in
                
                    if let lan = Int(contents[0]), let timeMode = Int(contents[1]),let time = Int(contents[2]),let paire = Int(contents[3]){
                        
                        let task = KCTOldBLETaskSystemSetting.init {[weak self] (tsk,error) -> (Void) in
                            self?.rspTextView.text = ResultContent(title: NSLocalizedString("系统设置", comment: ""), error: error, rspDes: nil)
                        }
                        task.language = lan
                        task.use12Hour = (timeMode != 0)
                        task.screenLightTime = time
                        task.needPairing = (paire != 0)
                        
                        //UI展示设置参数
                        self?.reqTextView.text = ReqContent(title: NSLocalizedString("系统设置", comment: ""), task: task)
                        
                        self?.bleShell.resume(baseTask: task)
                        
                    }else{
                        SVProgressHUD.showInfo(withStatus: NSLocalizedString("输入有误", comment: ""))
                    }
                
            }
            
        case .FindDevice://查找设备
            let task = KCTOldBLETaskFindDevice.init {[weak self] (tsk,error) -> (Void) in
                self?.rspTextView.text = ResultContent(title: NSLocalizedString("查找设备", comment: ""), error: error, rspDes: nil)
            }
            
            //UI展示设置参数
            reqTextView.text = ReqContent(title: NSLocalizedString("查找设备", comment: ""), task: task)
            
            bleShell.resume(baseTask: task)
            
        case .SetTime:

            self.showDateInput(title: NSLocalizedString("设置手表时间", comment: ""), message: NSLocalizedString("默认24小时制", comment: "")) {[weak self] (date) in
                let task = KCTOldBLETaskTimeSetting.init {[weak self](tsk,error) -> (Void) in
                    self?.rspTextView.text = ResultContent(title: NSLocalizedString("设置时间", comment: ""), error: error, rspDes: nil)
                }
                task.date = date
                task.mode = 0
                if self?.bleShell.currentPeripheral?.type == .Android{
                    task.area = NSTimeZone.init().description
                }
                
                //UI展示设置参数
                self?.reqTextView.text = ReqContent(title: NSLocalizedString("设置时间", comment: ""), task: task)
                
                self?.bleShell.resume(baseTask: task)
            }
            

        case .SetAlarm:
            let alarm0=KCTBLEAlarmClock.init(hour: 9, minut: 10, repeatMode: 1, label: 1, isOpen: true)
            let alarm1 = KCTBLEAlarmClock.init(hour: 10, minut: 11, repeatMode: 2, label: 1, isOpen: true)
            let alarm2 = KCTBLEAlarmClock.init(hour: 11, minut: 12, repeatMode: 4, label: 1, isOpen: true)
            let alarm3 = KCTBLEAlarmClock.init(hour: 12, minut: 13, repeatMode: 8, label: 1, isOpen: true)
            let alarm4 = KCTBLEAlarmClock.init(hour: 13, minut: 14, repeatMode: 16, label: 1, isOpen: true)
            
            let task = KCTOldBLETaskSetAlarms.init {[weak self] (tsk,error) -> (Void) in
                self?.rspTextView.text = ResultContent(title: NSLocalizedString("设置闹钟", comment: ""), error: error, rspDes: nil)
            }
            task.alarms = [alarm0,alarm1,alarm2,alarm3,alarm4]
            
            //UI展示设置参数
            reqTextView.text = ReqContent(title: NSLocalizedString("设置闹钟", comment: ""), task: task)
            
            bleShell.resume(baseTask: task)

        case .SetSportGoal://设置运动目标
            let alertVC = UIAlertController.init(title: NSLocalizedString("设置运动目标", comment: ""), message: nil, preferredStyle: .alert)
            alertVC.addTextField { (textField) in
                textField.placeholder = NSLocalizedString("运动目标", comment: "")
            }
            alertVC.addTextField { (textField) in
                textField.placeholder = NSLocalizedString("运动模式,0-记步,1-跑步,2-骑行,3-爬山", comment: "")
            }
            let comfirmAction = UIAlertAction.init(title: NSLocalizedString("确定", comment: ""), style: .default) {[weak alertVC] (action) in
                if let goalStr = alertVC?.textFields?.first?.text,let modeStr = alertVC?.textFields?.last?.text,let goal = Int(goalStr),let mode = Int(modeStr){
                    let task = KCTOldBLETaskSetSportGoal.init(completion: {[weak self] (tsk,error) -> (Void) in
                        self?.rspTextView.text = ResultContent(title: NSLocalizedString("设置运动目标", comment: ""), error: error, rspDes: nil)
                    })
                    task.goal = goal
                    task.sportMode = mode
                    
                    //UI展示设置参数
                    self.reqTextView.text = ReqContent(title: NSLocalizedString("设置运动目标", comment: ""), task: task)
                    
                    self.bleShell.resume(baseTask: task)
                }else{
                    SVProgressHUD.showInfo(withStatus: NSLocalizedString("输入有误", comment: ""))
                }
            }
            let cancelAction = UIAlertAction.init(title: NSLocalizedString("取消", comment: ""), style: .cancel, handler: nil)
            alertVC.addAction(comfirmAction)
            alertVC.addAction(cancelAction)
            self.present(alertVC, animated: true, completion: nil)
        case .SetSedentary://设置久坐提醒
            
            let placeholders = [NSLocalizedString("0关闭,1开启", comment: ""),
                                NSLocalizedString("开始时间(小时)", comment: ""),
                                NSLocalizedString("结束时间(小时)", comment: ""),
                                NSLocalizedString("重复。1-周一，2-周二，4-周三，8-周四...支持位或", comment: ""),
                                NSLocalizedString("久坐时间(分钟)", comment: ""),
                                NSLocalizedString("步数阈值", comment: "")]
            self.showMultiTextInput(title: NSLocalizedString("设置久坐提醒", comment: ""), message: nil, lines: placeholders.count, placeHolders: placeholders) {[weak self] (contents) in
                if let open = Int(contents[0]),let startHour = Int(contents[1]),let endHour = Int(contents[2]),let repeatMode = Int(contents[3]),let time = Int(contents[4]),let th = Int(contents[5]){
                    
                    let task = KCTOldBLETaskSetSedentary.init(completion: {[weak self] (tsk,error) -> (Void) in
                        self?.rspTextView.text = ResultContent(title: NSLocalizedString("设置久坐提醒", comment: ""), error: error, rspDes: nil)
                    })
                    task.enable = (open != 0)
                    task.startMomentHour = startHour
                    task.stopMomentHour = endHour
                    task.weekRepeat = repeatMode
                    task.sittingTime = time
                    task.threshold = th
                    
                    //UI展示设置参数
                    self?.reqTextView.text = ReqContent(title: NSLocalizedString("设置久坐提醒", comment: ""), task: task)
                    
                    self?.bleShell.resume(baseTask: task)
                }
            }
        case .SetDrinkRemind://设置喝水提醒
            
            let placeHolders = [NSLocalizedString("0-关闭,1-开启", comment: ""),
                                NSLocalizedString("开始时间:HH:mm", comment: ""),
                                NSLocalizedString("结束时间:HH:mm", comment: ""),
                                NSLocalizedString("重复。1-周一，2-周二，4-周三，8-周四...支持位或", comment: ""),
                                NSLocalizedString("喝水提醒间隔(分)", comment: "")]
            
            self.showMultiTextInput(title: NSLocalizedString("设置喝水提醒", comment: ""), message: nil, lines: placeHolders.count, placeHolders: placeHolders) {[weak self] (contents) in
                let startCmps = contents[1].components(separatedBy: ":")
                let endCmps = contents[2].components(separatedBy: ":")
                if startCmps.count > 1,endCmps.count > 1, let open = Int(contents[0]),let startH = Int(startCmps[0]),let startM = Int(startCmps[1]),let endH = Int(endCmps[0]),let endM = Int(endCmps[1]),let r = Int(contents[3]),let interval = Int(contents[4]) {
                    
                    let task = KCTOldBLETaskSetDrinkRemind.init {[weak self] (tsk,error) -> (Void) in
                        self?.rspTextView.text = ResultContent(title: NSLocalizedString("设置喝水提醒", comment: ""), error: error, rspDes: nil)
                    }
                    task.enable = (open != 0)
                    task.startMomentHour = startH
                    task.startMomentMinute = startM
                    task.stopMomentHour = endH
                    task.stopMomentMinute = endM
                    task.weekRepeat = r
                    task.interval = interval
                    
                    //UI展示设置参数
                    self?.reqTextView.text = ReqContent(title: NSLocalizedString("设置喝水提醒", comment: ""), task: task)
                    
                    self?.bleShell.resume(baseTask: task)
                    
                }else{
                    SVProgressHUD.showInfo(withStatus: NSLocalizedString("输入有误", comment: ""))
                }
            }
            
        case .SetPush://设置推送消息
            self.showTextInput(title: NSLocalizedString("设置消息推送", comment: ""), message: NSLocalizedString("设置方式见文档", comment: "")) {[weak self] (text) in
                
                if let push = Int(text) {
                    let task = KCTOldBLETaskSetMessagePush.init(completion: {[weak self] (tsk,error) -> (Void) in
                        self?.rspTextView.text = ResultContent(title: NSLocalizedString("设置消息推送", comment: ""), error: error, rspDes: nil)
                    })
                    task.pushSetting = push
                    
                    //UI展示设置参数
                    self?.reqTextView.text = ReqContent(title: NSLocalizedString("设置消息推送", comment: ""), task: task)
                    
                    self?.bleShell.resume(baseTask: task)
                }else{
                    SVProgressHUD.showInfo(withStatus: NSLocalizedString("输入有误", comment: ""))
                }
            }
        
        case .SetExtendedPush://设置扩展的消息推送
            
            self.showTextInput(title: NSLocalizedString("扩展的推送设置", comment: ""), message: NSLocalizedString("0关,1开。'001'表示关闭来电、打开短信和QQ。'0011'表示关闭来电和短信，打开QQ和微信。未填写的平台表示关闭。", comment: "")) {[weak self] (text) in
                
                let byteCount = text.count/8 + (text.count%8 > 0 ? 1:0)
                
                var value = Data.init(count: byteCount)
                
                for i in 0..<text.count {
                    
                    let start = String.Index.init(encodedOffset: i)
                    let end = String.Index.init(encodedOffset: i+1)
                    let str = String(text[start ..< end])
                    
                    if str == "0" {
                        value = self!._setData(data: value, atBitIndex: i, on: false)
                    }else if str == "1" {
                        value = self!._setData(data: value, atBitIndex: i, on: true)
                    }else{
                        SVProgressHUD.showInfo(withStatus: NSLocalizedString("非法的字符", comment: "")+"\(str)")
                        return
                    }
                }
                
                let task = KCTOldBLETaskSetExtendedMessagePush.init(settingData: value, completion: { (tsk, error) -> (Void) in
                    self?.rspTextView.text = ResultContent(title: NSLocalizedString("扩展的推送设置", comment: ""), error: error, rspDes: nil)
                })
                
                var content = ""
                for i in 0..<value.count {
                    
                    let v = value[i]
                    let str = String.init(format: "%.2x", v)
                    content.append(" \(str)")
                }
                
                self?.reqTextView.text = ReqContent(title: NSLocalizedString("扩展的推送设置", comment: ""), content: "Value的HEX值:\(content)")
                self?.bleShell.resume(baseTask: task)
            }
            
        case .ReqExtendedPush:// 读取扩展的推送设置
            self.reqTextView.text = ReqContent(title: NSLocalizedString("读取扩展的推送设置", comment: ""), content: "")
            
            let task = KCTOldBLETaskReadExtendedMessagePush.init {[weak self] (tsk, settingData, error) -> (Void) in
                
                var content:String?
                
                if error == nil {
                    
                    content = "HEXValue:\n"
                    for i in 0..<settingData!.count {
                        let hexStr = String.init(format: " %.2x", settingData![i])
                        content?.append(hexStr)
                    }
                }
                
                self?.rspTextView.text = ResultContent(title: NSLocalizedString("读取扩展的推送设置", comment: ""), error: error, rspDes: content)
            }
            
            self.bleShell.resume(baseTask: task)
    
        case .SendTextMessage:// 设置文本信息
            
            
            
            let placeHolders = [NSLocalizedString("信息类型。1-手机名称", comment: ""),
                                NSLocalizedString("文本内容", comment: "")]
            
            self.showMultiTextInput(title: NSLocalizedString("发送文本消息", comment: ""), message: NSLocalizedString("默认UTF-8编码。编码失败会回调错误", comment: ""), lines: placeHolders.count, placeHolders: placeHolders) {[weak self] (contents) in
                
                if let type = UInt8(contents[0]) {
                    
                    self?.reqTextView.text = ReqContent(title: NSLocalizedString("发送文本消息", comment: ""), content: "type=\(type)\nmessage=\(contents[1])")
                    
                    let task = KCTOldBLETaskSendTextMessage.init(type: type, message: contents[1], completion: {[weak self] (tsk, result, error) -> (Void) in
                        self?.rspTextView.text = ResultContent(title: NSLocalizedString("发送文本消息", comment: ""), error: error, rspDes: "result = \(result)")
                    })
                    self?.bleShell.resume(baseTask: task)
                }else{
                    SVProgressHUD.showInfo(withStatus: NSLocalizedString("输入有误", comment: ""))
                }
            }
            
        
        case .BPCalibrate://血压校准
            let phs = [NSLocalizedString("0-关闭,1-开启", comment: ""),
                       NSLocalizedString("收缩压", comment: ""),
                        NSLocalizedString("舒张压", comment: "")]
            self.showMultiTextInput(title: NSLocalizedString("血压校准", comment: ""), message: nil, lines: phs.count, placeHolders: nil) {[weak self] (contents) in
                
                if let openTag = UInt8(contents[0]),let sy = UInt8(contents[1]),let dia = UInt8(contents[2]){
                    
                    let task = KCTOldBLETaskBloodPressureCalibrate.init(open: (openTag != 0), systolicPressure: sy, diastolicPressure: dia, completion: {[weak self] (tsk,error) -> (Void) in
                        self?.rspTextView.text = ResultContent(title: NSLocalizedString("血压校准", comment: ""), error: error, rspDes: nil)
                    })
                    
                    self?.reqTextView.text = ReqContent(title: NSLocalizedString("血压校准", comment: ""), task: task)
                    self?.bleShell.resume(baseTask: task)
                    
                }else{
                    SVProgressHUD.showInfo(withStatus: NSLocalizedString("输入有误", comment: ""))
                }
                
                
            }
        case .SetMenstrualCycle:// 设置生理周期
            SVProgressHUD.show()
            let settings = KCTBLEMenstrualCycleSettings.init(lastStartDate: KCTBLEDate.init(date: Date.init()), lastLastsDays: 6, cycleDays: 28, durationDays: 7, alertEnable: true, alertTimeOffset: -60)
            let task = KCTOldBLETaskSetMenstrualCycle.init(settings: settings) {[weak self] (tsk, error) -> (Void) in
                SVProgressHUD.dismiss()
                self?.rspTextView.text = ResultContent(title: NSLocalizedString("设置生理周期", comment: ""), error: error, rspDes: nil)
            }
            self.reqTextView.text = ReqContent(title: NSLocalizedString("设置生理周期", comment: ""), task: task)
            task.resume()
            
        case .SetWeather://设置天气
            let placeHolders = [NSLocalizedString("测试天气数据的数量", comment: ""),
                               NSLocalizedString("是否支持当前温度。0-不支持，1-支持", comment: "")]
            self.showMultiTextInput(title: NSLocalizedString("设置天气", comment: ""), message: NSLocalizedString("测试天气数据的数量和是否支持当前温度，视不同设备的支持情况而定", comment: ""), lines: placeHolders.count, placeHolders: placeHolders) {[weak self] (contents) in
                if let count = Int(contents[0]), let support = Int(contents[1]){
                    
                    //创建测试天气数据
                    var weathers = Array<KCTBLEWeather>.init()
                    for _ in 0 ..< count{
                        let low = Int(arc4random())%40
                        let current = low + Int(arc4random()%30)
                        let high = current + Int(arc4random()%30)
                        let type = Int(arc4random()%5)
                        
                        let w = KCTBLEWeather.init()
                        w.lowTemp = low
                        w.currentTemp = current
                        w.highTemp = high
                        w.weatherType = type
                        weathers.append(w)
                    }
                    
                    let task = KCTOldBLETaskSetWeather.init(completion: { (tsk,error) -> (Void) in
                        self?.rspTextView.text = ResultContent(title: NSLocalizedString("设置天气", comment: ""), error: error, rspDes: nil)
                    })
                    task.supportCurrentTemp = (support != 0)
                    task.weathers = weathers
                    
                    // 在UI上展示推送的参数
                    self?.reqTextView.text = ReqContent(title: NSLocalizedString("设置天气", comment: ""), task: task)
                    
                    self?.bleShell.resume(baseTask: task)
                }else{
                    SVProgressHUD.showInfo(withStatus: NSLocalizedString("输入有误", comment: ""))
                }
            }
        case .SetAdvanceWeather://带地址的天气设置
            
            let phs = [NSLocalizedString("地址", comment: ""),
                       NSLocalizedString("测试天气数据的数量", comment: "")]
            
            self.showMultiTextInput(title: NSLocalizedString("带地址天气设置", comment: ""), message: NSLocalizedString("本例中的地址字符串采用Unicode编码。天气数据个数视设备的支持情况而定", comment: ""), lines: phs.count, placeHolders: phs) {[weak self] (contents) in
                if let addrData = contents[0].data(using: .unicode){
                    if let count = Int(contents[1]), count > 0 {
                        
                        //创建测试天气数据
                        var weathers = Array<KCTBLEWeather>.init()
                        for _ in 0 ..< count{
                            let isPositive = (arc4random()%2 == 0) ? 1 : (-1)
                            let low = Int(arc4random())%40 * isPositive
                            let current = low + Int(arc4random()%30)
                            let high = current + Int(arc4random()%30)
                            let type = Int(arc4random()%5)
                            
                            let w = KCTBLEWeather.init()
                            w.lowTemp = low
                            w.currentTemp = current
                            w.highTemp = high
                            w.weatherType = type
                            weathers.append(w)
                        }
                        
                        let task = KCTOldBLETaskSetAdvanceWeather.init(completion: { (tsk,error) -> (Void) in
                            self?.rspTextView.text = ResultContent(title: NSLocalizedString("带地址天气设置", comment: ""), error: error, rspDes: nil)
                        })
                        task.pushDate = KCTBLEDate.init(date: Date.init())
                        task.weathers = weathers
                        task.addrData = addrData
                        
                        // 在UI上展示推送的参数
                        self?.reqTextView.text = ReqContent(title: NSLocalizedString("带地址天气设置", comment: ""), task: task)//content
                        
                        self?.bleShell.resume(baseTask: task)
                        
                    }else{
                        SVProgressHUD.showInfo(withStatus: NSLocalizedString("天气个数输入有误", comment: ""))
                    }
                }else{
                    SVProgressHUD.showInfo(withStatus: NSLocalizedString("地址Unicode编码失败", comment: ""))
                }
            }
            
            self.showTextInput(title: NSLocalizedString("带地址天气设置", comment: ""), message: NSLocalizedString("填写推送测试天气的数量(不同设备有不同的支持情况)", comment: "")) {[weak self] (text) in
                if let count = Int(text){
                    
                    //创建测试天气数据
                    var weathers = Array<KCTBLEWeather>.init()
                    for _ in 0 ..< count{
                        let low = Int(arc4random())%40
                        let current = low + Int(arc4random()%30)
                        let high = current + Int(arc4random()%30)
                        let type = Int(arc4random()%5)
                        
                        let w = KCTBLEWeather.init()
                        w.lowTemp = low
                        w.currentTemp = current
                        w.highTemp = high
                        w.weatherType = type
                        weathers.append(w)
                    }
                    
                    let task = KCTOldBLETaskSetAdvanceWeather.init(completion: { (tsk,error) -> (Void) in
                        self?.rspTextView.text = ResultContent(title: NSLocalizedString("带地址天气设置", comment: ""), error: error, rspDes: nil)
                    })
                    task.pushDate = KCTBLEDate.init(date: Date.init())
                    task.weathers = weathers
                    task.addrData = NSLocalizedString("中国,重庆", comment: "").data(using: String.Encoding.unicode)!
                    self?.bleShell.resume(baseTask: task)
                }else{
                    SVProgressHUD.showInfo(withStatus: NSLocalizedString("输入有误", comment: ""))
                }
            }
        case .SetCameraOnOff://设置相机开启状态
            self.showTextInput(title: NSLocalizedString("设置相机开启状态", comment: ""), message: NSLocalizedString("告知设备目前手机端相机的开启状态。0-已关闭,1-已开启", comment: "")) {[weak self] (text) in
                if let open = Int(text){
                    let task = KCTOldBLETaskSetCameraOnOff.init(completion: {[weak self] (tsk,error) -> (Void) in
                        self?.rspTextView.text = ResultContent(title: NSLocalizedString("设置相机状态", comment: ""), error: error, rspDes: nil)
                    })
                    task.cameraOpened = (open != 0)
                    
                    //UI展示设置参数
                    self?.reqTextView.text = ReqContent(title: NSLocalizedString("设置相机状态", comment: ""), task: task)
                    
                    self?.bleShell.resume(baseTask: task)
                }else{
                    SVProgressHUD.showInfo(withStatus: NSLocalizedString("输入有误", comment: ""))
                }
            }
        case .SetGestureSceenOn://设置手势亮屏
            let phs = [NSLocalizedString("0-左手,1-右手", comment: ""),
                       NSLocalizedString("抬手亮屏.0-关闭,1-开启", comment: ""),
                       NSLocalizedString("翻腕亮屏.0-关闭,1-开启", comment: "")]
            self.showMultiTextInput(title: NSLocalizedString("设置手势亮屏", comment: ""), message: nil, lines: phs.count, placeHolders: phs) {[weak self] (contents) in
                if let hand = Int(contents[0]), let raise = Int(contents[1]),let flip = Int(contents[2]) {
                    let task = KCTOldBLETaskSetGestureScreenOn.init(completion: { (tsk,error) -> (Void) in
                        self?.rspTextView.text = ResultContent(title: NSLocalizedString("设置手势亮屏", comment: ""), error: error, rspDes: nil)
                    })
                    task.hand = (hand == 0) ? 0:1
                    task.flipOpen = (flip != 0)
                    task.raiseOpen = (raise != 0)
                    
                    //UI展示设置参数
                    self?.reqTextView.text = ReqContent(title: NSLocalizedString("设置手势亮屏", comment: ""), task: task)
                    
                    self?.bleShell.resume(baseTask: task)
                }else{
                    SVProgressHUD.showInfo(withStatus: NSLocalizedString("输入有误", comment: ""))
                }
            }
        case .ReqBindAuth:// 绑定授权
            self.showTextInput(title: NSLocalizedString("请求绑定授权", comment: ""), message: NSLocalizedString("0-不进行自动授权，需要用户在设备端选择；1-设备自动通过授权", comment: "")) {[weak self] (text) in
                if let input = Int(text) {
                    let task = KCTOldBLETaskReqBindAuthorization.init(autoAuth: input != 0, completion: { [weak self] (tsk, result, error) in
                        self?.rspTextView.text = ResultContent(title: NSLocalizedString("请求绑定授权", comment: ""), error: error, rspDes: NSLocalizedString("授权结果", comment: "")+":\(result)")
                    })
                    //UI展示设置参数
                    self?.reqTextView.text = ReqContent(title: NSLocalizedString("请求绑定授权", comment: ""), task: task)
                    
                    self?.bleShell.resume(baseTask: task)
                }else{
                    SVProgressHUD.showInfo(withStatus: NSLocalizedString("输入有误", comment: ""))
                }
            }
            
        case .SetDoNotDisturb://设置勿扰模式
            
            let phs = [NSLocalizedString("0-关闭,1-开启", comment: ""),
            NSLocalizedString("开始时间:HH:mm", comment: ""),
            NSLocalizedString("结束时间:HH:mm", comment: "")]
            
            self.showMultiTextInput(title: NSLocalizedString("设置勿扰", comment: ""), message: nil, lines: phs.count, placeHolders: phs) {[weak self] (contents) in
                
                let startCmps = contents[1].components(separatedBy: ":")
                let stopCmps = contents[2].components(separatedBy: ":")
                if let open = Int(contents[0]),startCmps.count > 1,stopCmps.count > 1,let startH = Int(startCmps[0]),let startM = Int(startCmps[1]),let stopH = Int(stopCmps[0]),let stopM = Int(stopCmps[1]){
                    
                    let task = KCTOldBLETaskSetDoNotDisturb.init {[weak self] (tsk,error) -> (Void) in
                        self?.rspTextView.text = ResultContent(title: NSLocalizedString("设置勿扰", comment: ""), error: error, rspDes: nil)
                    }
                    task.enable = (open != 0)
                    task.startHour = startH
                    task.startMinute = startM
                    task.stopHour = stopH
                    task.stopMinute = stopM
                    
                    //UI展示设置参数
                    self?.reqTextView.text = ReqContent(title: NSLocalizedString("设置勿扰", comment: ""), task: task)
                    
                    self?.bleShell.resume(baseTask: task)
                    
                }else{
                    SVProgressHUD.showInfo(withStatus: NSLocalizedString("输入有误", comment: ""))
                }
            }
            
        case .SetRemindMode://设置提醒模式
            self.showTextInput(title: NSLocalizedString("设置提醒模式", comment: ""), message: NSLocalizedString("1-亮屏，2-振动，3-亮屏+振动", comment: "")) {[weak self] (text) in
                if let mode = Int(text),mode > 0 ,mode < 4 {
                    let task = KCTOldBLETaskSetRemindMode.init(completion: { (tsk,error) -> (Void) in
                        self?.rspTextView.text = ResultContent(title: NSLocalizedString("设置提醒模式", comment: ""), error: error, rspDes: nil)
                    })
                    task.mode = mode
                    
                    //UI展示设置参数
                    self?.reqTextView.text = ReqContent(title: NSLocalizedString("设置提醒模式", comment: ""), task: task)
                    
                    self?.bleShell.resume(baseTask: task)
                }else{
                    SVProgressHUD.showInfo(withStatus: NSLocalizedString("输入有误", comment: ""))
                }
            }
        case .SetHRCheckConfig://设置心率监测
            
            let phs = [NSLocalizedString("0-关闭,1-开启", comment: ""),
            NSLocalizedString("开始时间:HH:mm", comment: ""),
            NSLocalizedString("结束时间:HH:mm", comment: ""),
                        NSLocalizedString("间隔(分)", comment: "")]
            
            self.showMultiTextInput(title: NSLocalizedString("心率监测设置", comment: ""), message: nil, lines: phs.count, placeHolders: phs) {[weak self] (contents) in
                let startCmps = contents[1].components(separatedBy: ":")
                let endCmps = contents[2].components(separatedBy: ":")
                if startCmps.count > 1,endCmps.count > 1,let open = Int(contents[0]),let startH = Int(startCmps[0]),let startM = Int(startCmps[1]),let stopH = Int(endCmps[0]),let stopM = Int(endCmps[1]),let interval = Int(contents[3]){
                    let task = KCTOldBLETaskSetHRCheckConfig.init(completion: { (tsk,error) -> (Void) in
                        self?.rspTextView.text = ResultContent(title: NSLocalizedString("心率监测设置", comment: ""), error: error, rspDes: nil)
                    })
                    task.enable = (open != 0)
                    task.startHour = startH
                    task.startMinute = startM
                    task.stopHour = stopH
                    task.stopMinute = stopM
                    task.interval = interval
                    
                    //UI展示设置参数
                    self?.reqTextView.text = ReqContent(title: NSLocalizedString("心率监测设置", comment: ""), task: task)
                    
                    self?.bleShell.resume(baseTask: task)
                }else{
                    SVProgressHUD.showInfo(withStatus: NSLocalizedString("输入有误", comment: ""))
                }
            }
            
            
        case .SetUnitsSystem://设置单位
            let phs = [NSLocalizedString("0-公制,1-英制", comment: ""),
                       NSLocalizedString("0-摄氏度,1-华氏度", comment: "")]
            self.showMultiTextInput(title: NSLocalizedString("设置单位", comment: ""), message: nil, lines: phs.count, placeHolders: phs) {[weak self] (contents) in
                
                if let measure = Int(contents[0]), let temp = Int(contents[1]){
                    
                    let task = KCTOldBLETaskSetUnitsSystem.init(completion: { (tsk,error) -> (Void) in
                        self?.rspTextView.text = ResultContent(title: NSLocalizedString("设置单位", comment: ""), error: error, rspDes: nil)
                    })
                    
                    task.measureUnitType = measure
                    task.temperatureUnitType = temp
                    
                    //UI展示设置参数
                    self?.reqTextView.text = ReqContent(title: NSLocalizedString("设置单位", comment: ""), task: task)
                    
                    self?.bleShell.resume(baseTask: task)
                }else{
                    SVProgressHUD.showInfo(withStatus: NSLocalizedString("输入有误", comment: ""))
                }
            }
            
            
        case .SetWeatherIndex://设置天气指数
            let phs = [NSLocalizedString("紫外线指数", comment: ""),
                        NSLocalizedString("大气压", comment: ""),
                        NSLocalizedString("海拔", comment: "")]
            self.showMultiTextInput(title: NSLocalizedString("设置天气指数", comment: ""), message: nil, lines: phs.count, placeHolders: phs) {[weak self] (contents) in
                
                if let uv = Int(contents[0]),let atom = Int(contents[1]),let al = Int(contents[2]){
                    
                    let task = KCTOldBLETaskSetWeatherIndex.init(completion: {[weak self] (tsk,error) -> (Void) in
                        self?.rspTextView.text = ResultContent(title: NSLocalizedString("设置天气指数", comment: ""), error: error, rspDes: nil)
                    })
                    task.UV = uv
                    task.atmos = atom
                    task.altitude = al
                    
                    //UI展示设置参数
                    self?.reqTextView.text = ReqContent(title: NSLocalizedString("设置天气指数", comment: ""), task: task)
                    
                    self?.bleShell.resume(baseTask: task)

                }else{
                    SVProgressHUD.showInfo(withStatus: NSLocalizedString("输入有误", comment: ""))
                }
            }
            
        case .InputAssitStart://协助输入开始
            let task = KCTOldBLETaskInputAsistStart.init {[weak self] (tsk,error) -> (Void) in
                self?.rspTextView.text = ResultContent(title: NSLocalizedString("开始协助输入", comment: ""), error: error, rspDes: nil)
            }
            
            //UI展示设置参数
            reqTextView.text = ReqContent(title: NSLocalizedString("开始协助输入", comment: ""), task: task)
            
            bleShell.resume(baseTask: task)
        case .InputAsistSendMsg://协助输入发送文本
            
            self.showTextInput(title: NSLocalizedString("协助输入", comment: ""), message: NSLocalizedString("该Demo中使用UTF8编码", comment: "")) {[weak self] (text) in
                
                if let data = text.data(using: .utf8){
                    let task = KCTOldBLETaskInputAsistSendMessage.init {[weak self] (tsk,error) -> (Void) in
                        self?.rspTextView.text = ResultContent(title: NSLocalizedString("协助输入", comment: ""), error: error, rspDes: nil)
                    }
                    task.messageData = data
                    
                    //UI展示设置参数
                    self?.reqTextView.text = "["+NSLocalizedString("协助输入", comment: "")+"]\n\ntext:\(text)"//ReqContent(title: "协助输入", task: task)
                    
                    self?.bleShell.resume(baseTask: task)
                }else{
                    SVProgressHUD.showInfo(withStatus: NSLocalizedString("UTF8编码失败", comment: ""))
                }
            }
        
        case .ReadFirmwareInfos://获取固件版本信息
            let task = KCTOldBLETaskReadFirmwareInfos.init {[weak self] (tsk, error, firmwareInfos) in

                self?.rspTextView.text = ResultContent(title: NSLocalizedString("获取固件信息", comment: ""), error: error, rspDes: "\(firmwareInfos?.yy_modelToJSONObject() ?? "")")
            }
            
            //UI展示设置参数
            reqTextView.text = ReqContent(title: NSLocalizedString("获取固件信息", comment: ""), task: task)
            
            task.resume()
            
        case .ReadBasicFirmwareInfos:// 获取基础固件信息
            let task = KCTOldBLETaskReadBasicFirmwareInfos.init {[weak self] (tsk, infosModel, error) in
                var content = ""
                let reqTitle = NSLocalizedString("获取基础固件信息", comment: "")
                if let err = error {
                    content = ResultContent(title:reqTitle , error: err, rspDes: nil)
                }else{
                    if let infos = infosModel{
                        content = ResultContent(title:reqTitle , error: nil, rspDes:"\(infos.yy_modelToJSONObject() ?? "")")
                    }else{
                        content = ResultContent(title:reqTitle , error: nil, rspDes: NSLocalizedString("设备不支持该指令", comment: ""))
                    }
                }
                self?.rspTextView.text = content
            }
            reqTextView.text = ReqContent(title: "获取基础固件信息", task: task)
            bleShell.resume(baseTask: task)
            task.resume()
            
        case .ReqProfileInfo:
            let task = KCTOldBLETaskReadProfile.init {[weak self] (tsk, profile, error) -> (Void) in
                self?.rspTextView.text = ResultContent(title: NSLocalizedString("获取配置信息", comment: ""), error: error, rspDes: "\(profile?.yy_modelToJSONObject() ?? "")")
            }
            
            //UI展示设置参数
            reqTextView.text = ReqContent(title: NSLocalizedString("获取配置信息", comment: ""), task: task)
            
            bleShell.resume(baseTask: task)
        
        case .ReqSettingInfo:
            let task = KCTOldBLETaskReadSettings.init {[weak self] (tsk,error, settingModel) -> (Void) in
                self?.rspTextView.text = ResultContent(title: NSLocalizedString("获取设置信息", comment: ""), error: error, rspDes: "\(settingModel?.yy_modelToJSONObject() ?? "")")
            }
            
            //UI展示设置参数
            reqTextView.text = ReqContent(title: NSLocalizedString("获取设置信息", comment: ""), task: task)
            
            bleShell.resume(baseTask: task)
        case .ReqPowerInfo:
            
            let task = KCTOldBLETaskReadPower.init {[weak self] (tsk, powerInfo, error) -> (Void) in
                self?.rspTextView.text = ResultContent(title: NSLocalizedString("获取电量", comment: ""), error: error, rspDes: "\(powerInfo?.yy_modelToJSONObject() ?? "")")
            }
            
            //UI展示设置参数
            reqTextView.text = ReqContent(title: NSLocalizedString("获取电量", comment: ""), task: task)
            
            bleShell.resume(baseTask: task)
            
        case .SyncHisSleep://同步历史睡眠
            self.showDateInput(title: NSLocalizedString("日期选择", comment: ""), message: nil) {[weak self] (date) in
                
                let task = KCTOldBLETaskSyncSleep.init(date: date) {[weak self] (tsk, error, group) in
                    self?.rspTextView.text = ResultContent(title: NSLocalizedString("同步历史睡眠", comment: ""), error: error, rspDes: "\(group?.yy_modelToJSONObject() ?? "")")
                }
                
                //UI展示设置参数
                self?.reqTextView.text = ReqContent(title: NSLocalizedString("同步历史睡眠", comment: ""), task: task)
                
                self?.bleShell.resume(baseTask: task)
                
            }

        case .SyncHisHeartRate://同步历史心率
            
            self.showDateInput(title: NSLocalizedString("日期选择", comment: ""), message: nil) {[weak self] (date) in
                
                let task = KCTOldBLETaskSyncHeartRate.init(date: date) {[weak self] (tsk, hrArray, error) in
                    let hrs = NSArray.init(array: hrArray)
                    self?.rspTextView.text = ResultContent(title: NSLocalizedString("同步历史心率", comment: ""), error: error, rspDes: "\(hrs.yy_modelToJSONObject() ?? "")")
                }
                
                //UI展示设置参数
                self?.reqTextView.text = ReqContent(title: NSLocalizedString("同步历史心率", comment: ""), task: task)
                
                self?.bleShell.resume(baseTask: task)
            }
            

        case .SyncHisStep://同步历史记步
            
            self.showDateInput(title: NSLocalizedString("日期选择", comment: ""), message: nil) {[weak self] (date) in
                
                let task = KCTOldBLETaskSyncSteps.init(date: date) {[weak self] (tsk, error, dailyStep) in
                    if let ds = dailyStep {
                        for unit in ds.stepsArray {
                            let totalStep = unit.runSteps + unit.walkSteps
                            if totalStep > 0 {
                                // 当步数不为0，但距离或者消耗卡路里为0时，可对距离和卡路里消耗进行估算。用户也可以通过自己的算法进行估算。
                                if unit.distance == 0.0 {
                                    unit.distance = KCTSportEstimateTools.Distance(gender: 1, height: 175, stepCount: totalStep)
                                }
                                if unit.kcal == 0.0 {
                                    unit.kcal = KCTSportEstimateTools.Calorie(weight: 70, stepCount: totalStep)
                                }
                            }
                        }
                    }
                    self?.rspTextView.text = ResultContent(title: NSLocalizedString("同步历史记步", comment: ""), error: error, rspDes: "\(dailyStep?.yy_modelToJSONObject() ?? "")")
                }
                
                //UI展示设置参数
                self?.reqTextView.text = ReqContent(title: NSLocalizedString("同步历史记步", comment: ""), task: task)
                
                self?.bleShell.resume(baseTask: task)
            }
            
        case .SyncHisSport://同步历史运动
            
            self.showDateInput(title: NSLocalizedString("日期选择", comment: ""), message: nil) {[weak self] (date) in
                
                SVProgressHUD.show(withStatus: NSLocalizedString("同步历史运动", comment: ""))
                let task = KCTOldBLETaskSyncSport.init(date: date) {[weak self] (tsk, error, array) in
                    SVProgressHUD.dismiss()
                    let ary = NSArray.init(array: array)
                    let des = "共\(ary.count)条\n\n" + "\(ary.yy_modelToJSONObject() ?? "")"
                    IPrint(NSLocalizedString("运动数据结果", comment: "")+"\n\(des)")
                    self?.rspTextView.text = ResultContent(title: NSLocalizedString("同步历史运动", comment: ""), error: error, rspDes: des)
                }
                
                //UI展示设置参数
                self?.reqTextView.text = ReqContent(title: NSLocalizedString("同步历史运动", comment: ""), task: task)
                
                self?.bleShell.resume(baseTask: task, timeout: 30)
            }
            
        case .SyncHisBP://历史血压
            self.showDateInput(title: NSLocalizedString("日期选择", comment: ""), message: nil) {[weak self] (date) in
                
                SVProgressHUD.show(withStatus: NSLocalizedString("同步历史血压", comment: ""))
                let task = KCTOldBLETaskSyncBP.init(date: date, completion: {[weak self] (tsk, bps, error) in
                    SVProgressHUD.dismiss()
                    let ary = NSArray.init(array: bps)
                    let des = "共\(ary.count)条\n\n" + "\(ary.yy_modelToJSONObject() ?? "")"
                    IPrint(NSLocalizedString("血压结果", comment: "")+"\n\(des)")
                    self?.rspTextView.text = ResultContent(title: NSLocalizedString("同步历史血压", comment: ""), error: error, rspDes: des)
                })
                
                //UI展示设置参数
                self?.reqTextView.text = ReqContent(title: NSLocalizedString("同步历史血压", comment: ""), task: task)
                
                self?.bleShell.resume(baseTask: task)
            }
            
            
        case .SyncHisBO://历史血氧
            self.showDateInput(title: NSLocalizedString("日期选择", comment: ""), message: nil) {[weak self] (date) in
                
                SVProgressHUD.show(withStatus: NSLocalizedString("同步历史血氧", comment: ""))
                let task = KCTOldBLETaskSyncBO.init(date: date) { (tsk, bos, error) in
                    SVProgressHUD.dismiss()
                    let ary = NSArray.init(array: bos)
                    let des = "共\(ary.count)条\n\n" + "\(ary.yy_modelToJSONObject() ?? "")"
                    IPrint(NSLocalizedString("血氧结果", comment: "")+"\n\(des)")
                    self?.rspTextView.text = ResultContent(title: NSLocalizedString("同步历史血氧", comment: ""), error: error, rspDes: des)
                }
                //UI展示设置参数
                self?.reqTextView.text = ReqContent(title: NSLocalizedString("同步历史血氧", comment: ""), task: task)
                self?.bleShell.resume(baseTask: task)
            }
            
        case .SyncHisPressure:// 同步历史压力
            
            self.showDateInput(title: NSLocalizedString("日期选择", comment: ""), message: nil) { [weak self](date) in
                
                SVProgressHUD.show(withStatus: NSLocalizedString("同步历史压力", comment: ""))
                
                let task = KCTOldBLETaskSyncPressure.init(date: date, completion: {[weak self] (tsk, pressures, error) in
                    SVProgressHUD.dismiss()
                    let ary = NSArray.init(array: pressures)
                    let des = "共\(ary.count)条\n\n" + "\(ary.yy_modelToJSONObject() ?? "")"
                    IPrint(NSLocalizedString("同步历史压力结果", comment: "")+"\n\(des)")
                    self?.rspTextView.text = ResultContent(title: NSLocalizedString("同步历史压力", comment: ""), error: error, rspDes: des)
                })
                
                self?.reqTextView.text = ReqContent(title: NSLocalizedString("同步历史压力", comment: ""), task: task)
                
                self?.bleShell.resume(baseTask: task)
            }
            
            
        case .SyncRealTimeSport://同步实时运动
            let task = KCTOldBLETaskSyncRealTimeSport.init {[weak self] (tsk, sport, error) in
                self?.rspTextView.text = ResultContent(title: NSLocalizedString("同步实时运动", comment: ""), error: error, rspDes: "\(sport?.yy_modelToJSONObject() ?? "")")
            }
            
            //UI展示设置参数
            reqTextView.text = ReqContent(title: NSLocalizedString("同步实时运动", comment: ""), task: task)
            
            bleShell.resume(baseTask: task)
//        case .SyncRealTimeSportMode:
//            let task = KCTOldBLETaskSyncRealTimeSportMode.init { (error) in
//
//            }
//            bleShell.resume(baseTask: task)
        case .SyncHisAnalogicECG://同步历史模拟心电
            SVProgressHUD.show(withStatus: NSLocalizedString("同步历史模拟心电", comment: ""))
            
            // 将获取该时间之后的心电数据
            let initialDate = KCTBLEDate.init()
            
            let task = KCTOldBLETaskSyncHisAnalogicECG.init(date: initialDate) {[weak self] (tsk, hisECGArray, error) in
                SVProgressHUD.dismiss()
                var des = "共\(hisECGArray.count)条\n\n"
                for i in 0..<hisECGArray.count {
                    
                    let ecg = hisECGArray[i]
                    
                    let time = "\(ecg.date.year)-\(ecg.date.month)-\(ecg.date.day) \(ecg.date.hour):\(ecg.date.minute):\(ecg.date.second)"
                    var hrDes = ""
                    for hr in ecg.hrValueArray {
                        if hrDes.count != 0{
                            hrDes.append(",")
                        }
                        hrDes.append("\(hr)")
                    }
                    let ecgDes = "[\(i)]" + time+":\n"+hrDes
                    des.append("\n\n"+ecgDes)
                }
                
                self?.rspTextView.text = ResultContent(title: NSLocalizedString("同步历史模拟心电", comment: ""), error: error, rspDes: des)
            }
            reqTextView.text = ReqContent(title: NSLocalizedString("同步历史模拟心电", comment: ""), task: task)
            bleShell.resume(baseTask: task)
            
        case .SyncHisTemp:// 同步历史体温
            
            self.showDateInput(title: "输入日期", message: "年月日时分秒") {[weak self] (date) in
                
                let task = KCTOldBLETaskSyncHisBodyTemperature.init {[weak self] (tsk, temps, error) in
                    self?.rspTextView.text = ResultContent(title: NSLocalizedString("同步历史体温", comment: ""), error: error, rspDes: "\(NSArray.init(array: temps).yy_modelToJSONObject() ?? "")")
                }
                task.date = date
                //UI展示设置参数
                self?.reqTextView.text = ReqContent(title: "同步历史体温", task: task)
                
                self?.bleShell.resume(baseTask: task)
            }
            
        case .SendUrgentNum:// 发送紧急号码
            self.showTextInput(title: NSLocalizedString("发送紧急号码", comment: ""), message: nil) {[weak self] (text) in
                
                let task = KCTOldBLETaskSendUrgentPhoneNum.init(phoneNum: text, completion: {[weak self] (tsk,error) -> (Void) in
                    self?.rspTextView.text = ResultContent(title: NSLocalizedString("发送紧急号码", comment: ""), error: error, rspDes: nil)
                })
                self?.reqTextView.text = ReqContent(title: NSLocalizedString("发送紧急号码", comment: ""), task: task)
                self?.bleShell.resume(baseTask: task)
            }
            
        case .ReqSmartSport://同步智能设备(Android)的历史运动
            self.showDateInput(title: NSLocalizedString("日期选择", comment: ""), message: nil) {[weak self] (date) in
                
                SVProgressHUD.show(withStatus: NSLocalizedString("同步Smart运动", comment: ""))
                let task = KCTOldBLETaskSmartSport.init(date: date) {[weak self] (tsk, sports, error) in
                    SVProgressHUD.dismiss()
                    let ary = NSArray.init(array: sports)
                    let des = "共\(ary.count)条\n\n" + "\(ary.yy_modelToJSONObject() ?? "")"
                    self?.rspTextView.text = ResultContent(title: NSLocalizedString("同步Smart运动", comment: ""), error: error, rspDes: des)
                }
                
                //UI展示设置参数
                self?.reqTextView.text = ReqContent(title: NSLocalizedString("同步Smart运动", comment: ""), task: task)
                
                //耗时操作，该任务的超时时间临时设为20秒
                self?.bleShell.resume(baseTask: task, timeout: 60.0)
            }
            
        case .SyncContacts://同步联系人
            
            // 清空任务队列
            self.sendContactTasks.removeAll()
            
            self.showTextInput(title: NSLocalizedString("同步联系人", comment: ""), message: NSLocalizedString("填写联系人数量", comment: "")) { (text) in
                
                if let count = Int(text), count > -1{
                    
                    var contacts = Array<KCTBLEContact>.init()
                    for i in 0..<count {
                        let contact = KCTBLEContact.init()
                        contact.name = NSLocalizedString("联系人", comment: "")+"\(i)"
                        contact.phoneNum = "\(i)"
                        contacts.append(contact)
                    }
                    
                    var reqContent = NSLocalizedString("联系人总数", comment: "")+":\(contacts.count)\n"
                    for i in 0..<contacts.count {
                        let str = contacts[i].name + " : " + contacts[i].phoneNum

                        if i > 0{
                            reqContent.append("\n")
                        }
                        reqContent.append(str)
                    }
                    self.reqTextView.text = ReqContent(title: NSLocalizedString("同步联系人", comment: ""), content: reqContent)
                    
                    // 将联系人分组，每组不超过10人。每一组创建一个发送任务
                    let groupMax = 10
                    var groupArray = Array<Array<KCTBLEContact>>.init()
                    let count = contacts.count/groupMax
                    for i in 0..<count {
                        let slice = contacts[i*groupMax..<i*groupMax+groupMax]
                        let group = Array<KCTBLEContact>.init(slice)
                        groupArray.append(group)
                    }
                    if (count * groupMax) < contacts.count {
                        //余下的为一组
                        let slice = contacts[count*groupMax..<contacts.count]
                        let group = Array<KCTBLEContact>.init(slice)
                        groupArray.append(group)
                    }
                    
                    // 根据分组，创建task
                    for i in 0..<groupArray.count{
                        let task = KCTOldBLETaskSendContacts.init(completion: {[weak self] (tsk, error) -> (Void) in
                            
                            guard let s = self else {
                                SVProgressHUD.showError(withStatus: NSLocalizedString("发送联系人终止:控制器已释放", comment: ""))
                                return
                            }
                            
                            if let t = tsk {
                                
                                if let err = error {
                                    self?.sendContactTasks.removeAll()
                                    SVProgressHUD.showError(withStatus: err.errInfo)
                                    self?.rspTextView.text = ResultContent(title: NSLocalizedString("发送联系人", comment: ""), error: err, rspDes: nil)
                                }
                                
                                var index = -1
                                for i in 0..<s.sendContactTasks.count {
                                    let tsk = s.sendContactTasks[i]
                                    if tsk === t {
                                        index = i
                                        break
                                    }
                                }
                                
                                if index > -1 {
                                    
                                    SVProgressHUD.show(withStatus: NSLocalizedString("发送进度", comment: "")+":\(index+1)/\(s.sendContactTasks.count)")
                                    
                                    if index == s.sendContactTasks.count - 1{
                                        //最后一个，发送完毕
                                        SVProgressHUD.showSuccess(withStatus: NSLocalizedString("发送完毕", comment: ""))
                                        s.rspTextView.text = ResultContent(title: NSLocalizedString("发送联系人", comment: ""), error: nil, rspDes: NSLocalizedString("发送完毕", comment: ""))
                                    }else{
                                        // 发送下一个
                                        let nextTsk = s.sendContactTasks[index + 1]
                                        s.bleShell.resume(baseTask: nextTsk)
                                    }
                                }
                                
                            }else{
                                
                                self?.sendContactTasks.removeAll()
                                
                                let err = KCTError.init()
                                err.errType = .Unknown
                                err.errInfo = NSLocalizedString("发送联系人异常:callback的task为空。", comment: "")
                                SVProgressHUD.showError(withStatus: err.errInfo)
                                self?.rspTextView.text = ResultContent(title: NSLocalizedString("发送联系人", comment: ""), error: err, rspDes: nil)
                                
                            }
                        })
                        task.contacts = groupArray[i]
                        self.sendContactTasks.append(task)
                    }
                    
                    if let firstTsk = self.sendContactTasks.first{
                        SVProgressHUD.show(withStatus: NSLocalizedString("进度", comment: "")+":0/\(self.sendContactTasks.count)")
                        self.bleShell.resume(baseTask: firstTsk)
                    }else{
                        SVProgressHUD.showInfo(withStatus: NSLocalizedString("没有要发送的联系人", comment: ""))
                    }
                    
                }else{
                    SVProgressHUD.showInfo(withStatus: NSLocalizedString("输入有误", comment: ""))
                }
            }
        case .SmartDialSelect://表盘选择
            self.showTextInput(title: NSLocalizedString("表盘选择", comment: ""), message: NSLocalizedString("填写表盘的索引号", comment: "")) {[weak self] (text) in
                if let num = UInt8(text){
                    let task = KCTOldBLETaskSmartDialSelect.init(serialNumber: num, completion: {[weak self] (tsk,error) -> (Void) in
                        self?.rspTextView.text = ResultContent(title: NSLocalizedString("表盘选择", comment: ""), error: error, rspDes: nil)
                    })
                    self?.bleShell.resume(baseTask: task)
                }else{
                    SVProgressHUD.showInfo(withStatus: NSLocalizedString("输入有误", comment: ""))
                }
            }
            
        case .SmartDialList:// 智能设备表盘列表
            let task = KCTOldBLETaskReadSmartDialList.init {[weak self] (tsk, indexes, error) -> (Void) in
                
                var str = "共\(indexes?.count ?? 0)条索引:"
                for i in 0..<(indexes?.count ?? 0){
                    if i > 0{
                        str.append(",")
                    }
                    str.append("\(indexes![i])")
                }
                self?.rspTextView.text = ResultContent(title: NSLocalizedString("获取Smart表盘", comment: ""), error: error, rspDes: str)
            }
            self.bleShell.resume(baseTask: task)
            
        case .SendQRString://发送二维码字符串
            self.showTextInput(title: NSLocalizedString("发送二维码字符串", comment: ""), message: nil) {[weak self] (text) in
                let task = KCTOldBLETaskSendQR.init(QRString: text, completion: {[weak self] (tsk,error) -> (Void) in
                    self?.rspTextView.text = ResultContent(title: NSLocalizedString("发送二维码字符串", comment: ""), error: error, rspDes: nil)
                })
                self?.reqTextView.text = ReqContent(title: NSLocalizedString("发送二维码字符串", comment: ""), task: task)
                self?.bleShell.resume(baseTask: task)
            }
            
        case .NordicUpgrade:
            let nordicVC = NordicUpgradeVC.init(nibName: "NordicUpgradeVC", bundle: Bundle.main)
            weakVC = nordicVC
            self.navigationController?.pushViewController(nordicVC, animated: true)
            
        case .DialogUpgreade:
            let dialogVC = DialogUpgradeVC.init(nibName: "DialogUpgradeVC", bundle: Bundle.main)
            self.navigationController?.pushViewController(dialogVC, animated: true)
            
        case .BKUpgrade:
            let bkVC = BKUpgradeVC.init(nibName: "BKUpgradeVC", bundle: Bundle.main)
            self.navigationController?.pushViewController(bkVC, animated: true)
            
        case .DialPush://表盘推送
            let dialPushVC = KCTDialPushVC.init(nibName: "KCTDialPushVC", bundle: Bundle.main)
            self.navigationController?.pushViewController(dialPushVC, animated: true)
            
        case .MedicineRemind://吃药提醒
            let remindVC = MedicineRemindVC.init(nibName: "MedicineRemindVC", bundle: Bundle.main)
            self.navigationController?.pushViewController(remindVC, animated: true)
            
        case .ESIM://ESIM
            let esimVC = ESIMVC.init(nibName: "ESIMVC", bundle: Bundle.main)
            self.navigationController?.pushViewController(esimVC, animated: true)
            
        case .PointerCorrect://指针校准
            let pointer = PointerCorrectVC.init(nibName: "PointerCorrectVC", bundle: Bundle.main)
            self.navigationController?.pushViewController(pointer, animated: true)
            
        case .ReqGPSRecord:
            let vc = KCTGPSDataSyncVC.init(nibName: "KCTGPSDataSyncVC", bundle: Bundle.main)
            self.navigationController?.pushViewController(vc, animated: true)
            
        case .Reboot://重启
            let task = KCTOldBLETaskReboot.init {[weak self] (tsk,error) -> (Void) in
                self?.rspTextView.text = ResultContent(title: NSLocalizedString("重启", comment: ""), error: error, rspDes: nil)
            }
            
            //UI展示设置参数
            reqTextView.text = ReqContent(title: NSLocalizedString("重启", comment: ""), task: task)
            
            bleShell.resume(baseTask: task)
        
        case .Reset://重置
            let task = KCTOldBLETaskReset.init {[weak self] (tsk,error) -> (Void) in
                self?.rspTextView.text = ResultContent(title: NSLocalizedString("重置", comment: ""), error: error, rspDes: nil)
            }
            
            //UI展示设置参数
            reqTextView.text = ReqContent(title: NSLocalizedString("重置", comment: ""), task: task)
            
            bleShell.resume(baseTask: task)
    
        case .AutoTest://自动测试
            let vc = BLEAutoTestVC.init(nibName: "BLEAutoTestVC", bundle: Bundle.main)
            self.navigationController?.pushViewController(vc, animated: true)
            
        case .ReqBind://请求绑定
            // mac:123456 userID:666666 注意长度必须是6个
            let task = KCTOldBLETaskReqBind.init(mac: [1,2,3,4,5,6],
                                                 userID: [6,6,6,6,6,6],
                                                 completion: {[weak self] (tsk,result,error) -> (Void) in
                self?.rspTextView.text = ResultContent(title: NSLocalizedString("请求绑定", comment: ""), error: error, rspDes: NSLocalizedString("请求绑定结果", comment: "")+":\(result)")
            })
            bleShell.resume(baseTask: task)
            
        case .ReqUnbind://请求解绑
            
            let task = KCTOldBLETaskReqUnBind.init(completion: {[weak self] (tsk,result,error) -> (Void) in
                self?.rspTextView.text = ResultContent(title: NSLocalizedString("请求解绑", comment: ""), error: error, rspDes: NSLocalizedString("请求解绑结果", comment: "")+":\(result)")
            })
            bleShell.resume(baseTask: task)
            

        default:
            SVProgressHUD.showInfo(withStatus: NSLocalizedString("未实现的功能", comment: "")+":\(funcName.rawValue)")
            IPrint(NSLocalizedString("未实现的功能", comment: "")+":\(funcName.rawValue)")
        }
        
        
    }
    
    
    
    
    private func _reqContent(reqDataArray:Array<Data>) -> String{
        var reqStr = ""
        for reqData in reqDataArray {
            let data = NSData.init(data: reqData)
            reqStr.append("\(data)\n")
        }
        return reqStr
    }
    

    private func _setData(data:Data,atBitIndex bitIndex:Int, on:Bool) -> Data{
        if data.count == 0 {
            return Data.init(data)
        }
        
        if bitIndex < data.count*8{
            
            let byteIndex = bitIndex/8
            
            let byte = data[byteIndex]
            
            let indexInByte = bitIndex%8
            
            var newValue:UInt8 = 0
            if on {
                newValue = (0x01 << indexInByte) | byte
            }else{
                newValue = (~(0x01 << indexInByte)) & byte
            }
            
            var newData = Data.init(data)
            newData[byteIndex] = newValue
            
            return newData
        }else{
            return Data.init(data)
        }
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle{
        
        if #available(iOS 13.0, *){
            // 为了在不含darkContent的xcode版本上运行
            if let style =  UIStatusBarStyle.init(rawValue: 3) {
                return style
            }else{
                return .default
            }
        }else{
            return .default
        }
    }
}

